var REGION = "region-view";
var CLASSIFICATION = "classification-view";
var TEAM = "team-view";
var NEWS = "news-view";
var SCORE = "score-view";
var MENU = "menu-view";
var RESULTS = "results-view";
var ABOUT = "about-view";

var READ = "readNewDiv";
var READCONTENTS = "readNewDivContents";
var NEWS = "newsDiv";
var NEWSCONTENTS = "newsDivContents";

var LOADING = "mainLoading";
var MAINERROR = "mainError";
var MAININFO = "mainInfo";

/**
 * URL of the application
 */
var urlLiveScore = "http://www.fifa.com/worldfootball/worldmatchcentre/";
var urlMatches = "http://www.fifa.com/worldcup/preliminaries/matches/";
var urlCupNews = "http://www.fifa.com/worldcup/news/rss.xml";

var countries = null;
var selectedCountry = null;

var menuDiv;
var classificationDiv;
var regionDiv;
var newsDiv;
var scoreDiv;
var teamResultsDiv;
var teamDiv;
var aboutDiv;

var readDiv;
var readDivContents;
var newsDiv;
var newsDivContents;

var loadingDiv;
var mainErrorDiv;
var mainInfoDiv;

var typeBack;

/**
 * Loads data at the start of the application.
 */
function onLoadData() {
	try {
		menuDiv = document.getElementById(MENU);
		classificationDiv = document.getElementById(CLASSIFICATION);
		regionDiv = document.getElementById(REGION);
		teamDiv = document.getElementById(TEAM);
		scoreDiv = document.getElementById(SCORE);
		teamResultsDiv = document.getElementById(RESULTS);
		aboutDiv = document.getElementById(ABOUT);

		readDiv = document.getElementById(READ);
		readDivContents = document.getElementById(READCONTENTS);
		newsDiv = document.getElementById(NEWS);
		newsDivContents = document.getElementById(NEWSCONTENTS);

		loadingDiv = document.getElementById(LOADING);
		mainErrorDiv = document.getElementById(MAINERROR);
		mainInfoDiv = document.getElementById(MAININFO);

		showLoading();
		loadCountries();
	} catch (err) {
		showError(err, "onLoadData()", 1);
	}
}

/**
 * Loads all the countries and stores it in the contries variable
 */
function loadCountries() {
	try {
		var networkUtils = new NetworkUtils();

		networkUtils.makeHttpRequest(urlMatches,
				networkUtils.REQUEST_METHOD_GET, null, 'HTML',
				loadCountriesCallBack, null);
	} catch (e) {
		showError(e, "loadCountries()", 1);
	}
}

function loadCountriesCallBack(xmlNode, args) {
	if (xmlNode == "networkError" || xmlNode == "timeout") {
		showError(xmlNode, "loadCountriesCallBack(xmlNode, args)", 1);
		return;
	}

	try {
		var pattern = /<select\s+id="fwcSearchBarCountry".*>*?<\/select><select/g;
		var txtCountries = xmlNode.match(pattern) + "";

		txtCountries = txtCountries.substring(0, txtCountries.length - 7);

		var jsTmp = xml2json(new DOMParser().parseFromString(txtCountries,
				"text/xml").firstChild);

		var results = new Array();
		
		for (var i = 1; i < jsTmp.option.length; i++) {
			var option = jsTmp.option[i];

			var json = {
				name : option.nodeValue,
				url :'http://www.fifa.com' + option.value
			}
			results.push(json);
		}
		countries = results;
		loadCountriesAbreviation();
	} catch (err) {
		showError(err, "loadCountriesCallBack()", 1);
	}
}

/**
 * Loads the countries abreviation and stores it in the countries variable
 */
function loadCountriesAbreviation() {
	try {
		var networkUtils = new NetworkUtils();

		networkUtils.makeHttpRequest(
				"http://www.fifa.com/newscentre/rssfeeds/index.html",
				networkUtils.REQUEST_METHOD_GET, null, 'HTML',
				loadCountriesAbreviationCallBack, null);
	} catch (e) {
		showError(e, "loadCountriesAbreviation()", 1);
	}
}

function loadCountriesAbreviationCallBack(xmlNode, args) {
	if (xmlNode == "networkError" || xmlNode == "timeout") {
		showError(xmlNode, "loadCountriesAbreviationCallBack(xmlNode, args)", 1);
		return;
	}

	try {
		var pattern = /<select\s+id="maRSSList".*>(.|\n|\r)*?<\/select>/g;
		var txtCountriesAbr = xmlNode.match(pattern) + "";

		var jsTmp = xml2json(new DOMParser().parseFromString(txtCountriesAbr,
				"text/xml").firstChild);

		var results = new Array();
		for ( var i = 1; i < jsTmp.option.length; i++) {
			var option = jsTmp.option[i];

			for ( var x = 0; x < countries.length; x++) {
				var jsonCountry = countries[x];

				var idAbr = option.value.search("=");
				var abr = option.value.substring(idAbr + 1, idAbr + 4);

				if (option.nodeValue == jsonCountry.name) {
					var json = {
						name :jsonCountry.name,
						url :jsonCountry.url,
						abreviation :abr.toUpperCase(),
						urlRSS :'http://www.fifa.com' + option.value
					}
					results.push(json);
				}
			}
		}
		countries = results;

		showMenu();
	} catch (err) {
		showError(err, "loadCountriesAbreviationCallBack()", 1);
	}
}

/**
 * Clean all the application div's
 */
function clearScreen() {
	try {
		menuDiv.style.display = "none";
		classificationDiv.style.display = "none";
		regionDiv.style.display = "none";
		teamDiv.style.display = "none";
		scoreDiv.style.display = "none";
		teamResultsDiv.style.display = "none";
		aboutDiv.style.display = "none";

		readDiv.style.display = "none";
		newsDiv.style.display = "none";

		mainErrorDiv.style.display = "none";
		mainInfoDiv.style.display = "none";
		loadingDiv.style.display = "none";
	} catch (e) {
		showError(e, "clearScreen()", 1);
	}
}

/**
 * Displays or not the button to return to the menu.
 * 
 * @param flag -
 *            number (type of option)
 */
function displayBack(flag) {
	try {
		var imgBack = document.getElementById("imgBack");
		typeBack = flag;
		if (flag == 0) {
			imgBack.style.display = "none";
		} else if (flag >= 1) {
			imgBack.style.display = "block";
		}
	} catch (err) {
		showError(err, "displayBack(" + flag + ")", 1);
	}
}

/**
 * Displays the header text of each div.
 * 
 * @param name -
 *            string(name of screen)
 */
function displayCaption(name) {
	try {
		var tdCaption = document.getElementById('txtCaption');
		tdCaption.innerHTML = name;
	} catch (err) {
		showError(err, "displayCaption(" + name + ")", 1);
	}
}

/**
 * Displays the DIV sent as parameter
 * 
 * @param div -
 *            DIV
 */
function displayDiv(div) {
	try {
		clearScreen();
		div.style.display = "block";
	} catch (err) {
		showError(err, "displayDiv(" + div.id + ")", 1);
	}
}

/**
 * Shows the loading screen
 */
function showLoading() {
	try {
		displayDiv(loadingDiv);
		displayBack(0);
	} catch (err) {
		showError(err, "showLoading()", 1);
	}
}

/**
 * Shows the classification screen
 */
function showClassification() {
	try {
		displayCaption("Classification");
		showLoading();
		requestClassification();
	} catch (err) {
		showError(err, "showClassification()", 1);
	}
}

/**
 * Shows the region selection screen
 */
function showRegion() {
	try {
		displayCaption("Regions");
		showLoading();
		selectRegion();
	} catch (err) {
		showError(err, "showRegion()", 1);
	}
}

/**
 * Shows the team selection screen
 */
function showTeam() {
	try {
		displayCaption("Your Team");
		showLoading();
		searchTeam();
	} catch (err) {
		showError(err, "showTeam()", 1);
	}
}

/**
 * Shows the news screen
 */
function showNews() {
	try {
		displayCaption("News");
		displayDiv(newsDiv);
		displayBack(1);
	} catch (err) {
		showError(err, "showNews()", 1);
	}
}

/**
 * Shows the live scores screen
 */
function showScore() {
	try {
		displayCaption("Live Score");
		showLoading();
		requestScore();
	} catch (err) {
		showError(err, "showScore()", 1);
	}
}

/**
 * Shows the about screen
 */
function showAbout() {
	try {
		displayCaption("About");
		showLoading();
		displayBack(1);

		displayDiv(aboutDiv);
	} catch (err) {
		showError(err, "showAbout()", 1);
	}
}

/**
 * Shows the menu screen
 */
function showMenu() {
	try {
		displayBack(-1);
		displayCaption("World Cup 2010");

		displayDiv(menuDiv);

		displayBack(0);
	} catch (err) {
		showError(err, "showMenu()", 1);
	}
}

/**
 * Shows the selected news item
 */
function showRead() {
	try {
		displayBack(1);

		var component = newsDivContents.component;

		if (component.selectedIndex != -1) {
			rssReaderShowHide(NEWSCONTENTS, 'row_' + component.selectedIndex);
		}
	} catch (err) {
		showError(err, "showMenu()", 1);
	}
}

/**
 * Shows the error screen
 * 
 * @param nameFunction - String (name of the function)
 */
function showError(nameFunction) {
	displayCaption("Error");
	showError("unknown", nameFunction);
}

/**
 * Shows the error screen
 * @param msg - String (error message)
 * @param nameFunction - String (name of the function)
 * @param numberDisplayBack - Number(number of the display back)
 */
function showError(msg, nameFunction, numberDisplayBack) {
 	displayCaption("Error");
 	if(!numberDisplayBack){
 		displayBack(1);
 	}else{
 		displayBack(numberDisplayBack);
 	}

 	displayDiv(mainErrorDiv);
 	
 	var errorDiv;
 	errorDiv = '<table class="popup" border="2" bordercolor="FFFFFF">';
 	errorDiv += '<tr height="20px">';
 	errorDiv += '<td align="left">Function: ' + nameFunction +  ' </td>';
 	errorDiv += '</tr>';
 	errorDiv += '<tr>';
 	errorDiv += '<td valign="top">Description: ' + msg +  ' </td>';
 	errorDiv += '</tr>';
 	errorDiv += '</table>';
 	
 	mainErrorDiv.innerHTML = errorDiv;
 }
 
/**
* Shows the info screen
* @param msg - String (info message)
* @param nameScreen - String (name of the Screen)
* @param numberDisplayBack - Number(number of the display back)
*/
function showInfo(msg, nameScreen, numberDisplayBack) {
  	displayCaption("Info");
	if(!numberDisplayBack){
		displayBack(1);
	}else{
		displayBack(numberDisplayBack);
	}

	displayDiv(mainInfoDiv);

	var showInfoDiv;
	showInfoDiv = '<table class="popup" border="2" bordercolor="FFFFFF">';
	showInfoDiv += '<tr height="20px">';
	showInfoDiv += '<td align="left">Screen: ' + nameScreen +  ' </td>';
	showInfoDiv += '</tr>';
	showInfoDiv += '<tr>';
	showInfoDiv += '<td valign="top">Description: ' + msg +  ' </td>';
	showInfoDiv += '</tr>';
	showInfoDiv += '</table>';
  	
	mainInfoDiv.innerHTML = showInfoDiv;
}

/**
 * Return to menus
 */
function backMenu() {
	try {
		if (typeBack == 1) {
			showMenu();
		} else if (typeBack == 2) {
			showTeam();
		} else if (typeBack == 3) {
			displayCaption("Regions")
			selectRegion();
		}
	} catch (err) {
		showError(err, "showMenu()", 1);
	}
}

/**
 * Selects the available regions
 */
function selectRegion() {
	try {
		clearScreen();
		regionDiv.style.display = "block";

		var selectRegion = '<br>';
		selectRegion += '<select id="slcRegion" class="cssRegions" >';
		selectRegion += '<option class="one" value="undefined" label="Select a Region"/>';
		selectRegion += '<option class="two" value="http://www.fifa.com/worldcup/preliminaries/africa/standings/index.html" label="Africa"/>';
		selectRegion += '<option class="one" value="http://www.fifa.com/worldcup/preliminaries/asia/standings/index.html" label="Asia"/>';
		selectRegion += '<option class="two" value="http://www.fifa.com/worldcup/preliminaries/europe/standings/index.html" label="Europe"/>';
		selectRegion += '<option class="one" value="http://www.fifa.com/worldcup/preliminaries/nccamerica/standings/index.html" label="North, Central America and Caribbean"/>';
		selectRegion += '<option class="two" value="http://www.fifa.com/worldcup/preliminaries/oceania/standings/index.html" label="Oceania"/>';
		selectRegion += '<option class="one" value="http://www.fifa.com/worldcup/preliminaries/southamerica/standings/index.html" label="South America"/>';
		selectRegion += '</select>';

		var btnOk = '<br><br><br><div align="center"><img id="imgOk" src="img/btnOk.gif" onclick="showClassification();" > </div>';

		regionDiv.innerHTML = selectRegion + btnOk;
		displayBack(1);
	} catch (e) {
		showError(e, "selectRegion()", 1);
	}
}

/**
 * Request the classification data
 */
function requestClassification() {
	try {
		var urlRegionSelect = document.getElementById("slcRegion").value;
		if (urlRegionSelect == "undefined") {
			showRegion();
			return;
		}

		var networkUtils = new NetworkUtils();

		networkUtils.makeHttpRequest(urlRegionSelect,
				networkUtils.REQUEST_METHOD_GET, null, 'TEXT',
				requestClassificationCallBack, null);
	} catch (e) {
		showError(e, "requestClassification()", 1);
	}
}

function requestClassificationCallBack(xmlNode, args) {
	try {
		if (xmlNode == "networkError" || xmlNode == "timeout") {
			showError(xmlNode, "populateFeedClassificationGroup(xmlNode, args)", 1);
			return;
		}

		displayDiv(classificationDiv);
		displayBack(3);

		var groups = new Array();

		var idGroupDetail = xmlNode.search("tGroupDetail");
		var txtClassification = xmlNode.substring(idGroupDetail);

		var moreGroup = txtClassification.search('Group');
		while (moreGroup != -1) {
			var results = new Array();
			var idGroup = txtClassification.search('<table summary="Group');
			var idCloseGroup = txtClassification.search("</table>");
			var tableGroup = txtClassification.substring(idGroup,
					idCloseGroup + 8);
			var txtClassification = txtClassification
					.substring(idCloseGroup + 8);

			moreGroup = txtClassification.search('<table summary="Group');

			var jsTmp = xml2json(new DOMParser().parseFromString(tableGroup,
					"text/xml").firstChild);

			var tr = jsTmp.thead.tr;

			var cabecalhoJson = {
				team :tr.td[1].nodeValue,
				mp :tr.td[2].abbr.nodeValue,
				w :tr.td[3].abbr.nodeValue,
				d :tr.td[4].abbr.nodeValue,
				l :tr.td[5].abbr.nodeValue,
				f :tr.td[6].abbr.nodeValue,
				ga :tr.td[7].abbr.nodeValue,
				pts :tr.td[8].abbr.nodeValue
			}
			results.push(cabecalhoJson);

			for ( var i = 0; i < jsTmp.tbody.tr.length; i++) {
				var tr = jsTmp.tbody.tr[i];
				var resultJson = {
					team :tr.td[1].a.nodeValue,
					mp :tr.td[2].nodeValue,
					w :tr.td[3].nodeValue,
					d :tr.td[4].nodeValue,
					l :tr.td[5].nodeValue,
					f :tr.td[6].nodeValue,
					ga :tr.td[7].nodeValue,
					pts :tr.td[8].nodeValue
				}
				results.push(resultJson);
			}

			var teste = (jsTmp.caption ? jsTmp.caption.nodeValue : "");
			var group = {
				caption :teste,
				elements :results
			}
			groups.push(group);
		}
		makeTableClassificationResults(groups);
	} catch (err) {
		showError(err, "populateFeedClassification(xmlNode, args)", 1);
	}
}

/**
 * Creates the table of classification
 */
function makeTableClassificationResults(groups) {
	try {
		var fullGrups = "";
		for ( var x = 0; x < groups.length; x++) {
			var myObjectGroup = groups[x];

			if (x % 2 != 0) {
				cssTable = "headerClassificationUp";
			} else {
				cssTable = "headerClassificationDown";
			}

			var classificationResults = '<table class="tableInformation" border="1" width = "100%" >';
			if (myObjectGroup.caption != "") {
				classificationResults += "<caption><b>" + myObjectGroup.caption
						+ "</b></caption>";
			}

			var results = myObjectGroup.elements;
			var myHeader = results[0];

			classificationResults += '<tr class="' + cssTable + '">';
			classificationResults += '<td width="38%">' + myHeader.team + '</td>';
			classificationResults += '<td>' + myHeader.mp + '</td>';
			classificationResults += '<td>' + myHeader.w + '</td>';
			classificationResults += '<td>' + myHeader.d + '</td>';
			classificationResults += '<td>' + myHeader.l + '</td>';
			classificationResults += '<td>' + myHeader.f + '</td>';
			classificationResults += '<td>' + myHeader.ga + '</td>';
			classificationResults += '<td>' + myHeader.pts + '</td>';
			classificationResults += '</tr>';

			for ( var i = 1; i < results.length; i++) {
				var myObject = results[i];
				classificationResults += '<tr class="down">';
				classificationResults += '<td>' + myObject.team + '</td>';
				classificationResults += '<td align="center">' + myObject.mp + '</td>';
				classificationResults += '<td align="center">' + myObject.w + '</td>';
				classificationResults += '<td align="center">' + myObject.d + '</td>';
				classificationResults += '<td align="center">' + myObject.l + '</td>';
				classificationResults += '<td align="center">' + myObject.f + '</td>';
				classificationResults += '<td align="center">' + myObject.ga + '</td>';
				classificationResults += '<td align="center">' + myObject.pts + '</td>';
				classificationResults += '</tr>';
			}
			classificationResults += '</table>';

			fullGrups += classificationResults;

		}
		classificationDiv.innerHTML = fullGrups;
	} catch (err) {
		showError(err, "makeTableClassificationResults()", 1);
	}
}

/**
 * Request the fixtures and results data
 */
function requestResults() {
	try {
		showLoading();

		var networkUtils = new NetworkUtils();

		var url = document.getElementById('selectCountries').value;
		
		if(!url){
			showInfo("Select a country!", "Your Team", 2);
			return;
		}
		
		var indexEnd = url.search(";");
		url = url.substring(0, indexEnd);

		networkUtils.makeHttpRequest(url, networkUtils.REQUEST_METHOD_GET,
				null, 'HTML', requestResultsCallBack, null);
	} catch (e) {
		showError(e, "requestResults()", 2);
	}
}

function requestResultsCallBack(xmlNode, args) {
	if (xmlNode == "networkError" || xmlNode == "timeout") {
		showError(xmlNode, "populateFeedResults((xmlNode, args)", 1);
		return;
	}
	displayDiv(teamResultsDiv);

	try {
		var pattern = /<table\s+(.*)\s+class\s*=\s*"fixture".*>(.|\n|\r)*?<\/table>/g;
		var txtFixturesResults = xmlNode.match(pattern) + "";

		var jsTmp = xml2json(new DOMParser().parseFromString(
				txtFixturesResults, "text/xml").firstChild);

		var results = new Array();
		for ( var i = 0; i < jsTmp.tbody.tr.length; i++) {
			var tr = jsTmp.tbody.tr[i];
			
			var json = {
				data : tr.td[0].span.nodeValue,
				local : tr.td[1].nodeValue,
				urlImgHome : "http://www.fifa.com" + tr.td[2].a.img.src,
				home : tr.td[3].a.nodeValue,
				score : tr.td[4].a ? tr.td[4].a.nodeValue : '-',
				away : tr.td[5].a.nodeValue,
				urlImgAway : "http://www.fifa.com" + tr.td[6].a.img.src
			}
			results.push(json);
		}

		makeTableFixturesResults(results);
	} catch (err) {
		showError(err, "requestResultsCallBack()", 1);
	}
}

/**
 * Creates the table of fixtures and results
 */
function makeTableFixturesResults(results) {
	try {
		var fixturesResults = '<table class="tableInformation" border="1" width = "100%" >';
		var cssTable = null;
		var cssDate = null;

		for ( var i = 0; i < results.length; i++) {
			var json = results[i];

			if (i % 2 != 0) {
				cssTable = "up";
				cssDate = "upDate";
			} else {
				cssTable = "down";
				cssDate = "downDate";
			}

			fixturesResults += '<tr class="' + cssDate + '" >';
			fixturesResults += '<td align = "center" >' + json.data.substring(
					0, 9) + '</td>';
			fixturesResults += '</tr>';

			fixturesResults += '<tr>';
			fixturesResults += '<td align = "center" >';
			fixturesResults += '<table border = "0" cellspacing = "1" width = "100%">';
			fixturesResults += '<tr>';
			fixturesResults += '<td><img width="19" height="13" src="' + json.urlImgHome + '"/></td>';
			fixturesResults += '<th width="50%" >Home</th>';
			fixturesResults += '<th width="50%" >Away</th>';
			fixturesResults += '<td><img width="19" height="13" src="' + json.urlImgAway + '"/></td>';
			fixturesResults += '</tr>';
			fixturesResults += '</table>';
			fixturesResults += '</td>';
			fixturesResults += '</tr>';

			fixturesResults += '<tr>';

			fixturesResults += '<td>';
			fixturesResults += '<table class="tableScore" border = "1" width = "100%">';
			fixturesResults += '<tr>';
			fixturesResults += '<td width="45%" align="center" >' + json.home + '</td>';

			var score = json.score;
			var idEndScore = score.indexOf('(');
			if (idEndScore != -1) {
				fixturesResults += '<th width="10%" align="center" >' + score.substring(0, idEndScore) + '</th>';
			} else {
				fixturesResults += '<th width="10%" align="center" > ' + score + '</th>';
			}

			fixturesResults += '<td width="45%" align="center" >' + json.away + '</td>';
			fixturesResults += '</tr>';
			fixturesResults += '</table>';
			fixturesResults += '</td>';
			fixturesResults += '</tr>';

			fixturesResults += '<tr class="' + cssTable + '" >';

			fixturesResults += '<td>';
			fixturesResults += '<table border = "0" cellspacing = "1" width = "100%">';
			fixturesResults += '<tr>';
			fixturesResults += '<th width="5%" >City:</th>';
			fixturesResults += '<td width="*%" >' + json.local + '</td>';
			fixturesResults += '</tr>';
			fixturesResults += '</table>';
			fixturesResults += '</td>';
			fixturesResults += '</tr>';
		}
		fixturesResults += '</table>';

		teamResultsDiv.innerHTML = fixturesResults;
		displayBack(2);
	} catch (err) {
		showError(err, "makeTableFixturesResults()", 1);
	}
}

/**
 * Request the live score data
 */
function requestScore() {
	try {
		var networkUtils = new NetworkUtils();

		networkUtils.makeHttpRequest(urlLiveScore,
				networkUtils.REQUEST_METHOD_GET, null, 'HTML',
				requestScoreCallBack, null);
	} catch (e) {
		showError(e, "requestScore()", 1);
	}
}

function requestScoreCallBack(xmlNode, args) {
	try {
		if (xmlNode == "networkError" || xmlNode == "timeout") {
			showError(xmlNode, "populateFeedScore(xmlNode, args)", 1);
			return;
		}

		displayDiv(scoreDiv);

		var results = new Array();

		var idBegin = xmlNode.search('<div class="wmcMatchesContainer');
		if (idBegin != -1) {
			var aux = xmlNode.substring(idBegin);
			var idFinisher = aux.search('<div class="ft"> </div></div></div>');
			var txtMatches = aux.substring(0, idFinisher + 35);

			var jsTmp = xml2json(new DOMParser().parseFromString(txtMatches,
					"text/xml").firstChild);

			for ( var i = 0; i < jsTmp.div.length; i++) {
				var match = jsTmp.div[i];
				
				if (match.div[1].div[0].div) {
					var state = match.div[1].div[0].div.div[0].div.nodeValue;
					var time = match.div[1].div[0].div.div[1].nodeValue;
				} else {
					var state = match.div[1].div[0].span.div[0].div.nodeValue;
					var time = match.div[1].div[0].span.div[1].nodeValue;
				}

				var nameTeamHome = match.div[1].div[1].div.nodeValue;
				var goalsMarkedHome = "";
				if (match.div[1].div[1].ul.li.length) {
					for ( var j = 0; j < match.div[1].div[1].ul.li.length; j++) {
						goalsMarkedHome += "<br>"
								+ match.div[1].div[1].ul.li[j].nodeValue;
					}
					goalsMarkedHome = goalsMarkedHome.substring(4);
				} else {
					goalsMarkedHome = match.div[1].div[1].ul.li.nodeValue;
					if (!goalsMarkedHome) {
						goalsMarkedHome = "";
					}
				}

				var score = match.div[1].div[2].nodeValue;

				var nameTeamAway = match.div[1].div[3].div.nodeValue;
				var goalsMarkedAway = "";
				if (match.div[1].div[3].ul.li.length) {
					for ( var k = 0; k < match.div[1].div[3].ul.li.length; k++) {
						goalsMarkedAway += "<br>"
								+ match.div[1].div[3].ul.li[k].nodeValue;
					}
					goalsMarkedAway = goalsMarkedAway.substring(4);
				} else {
					goalsMarkedAway = match.div[1].div[3].ul.li.nodeValue;
					if (!goalsMarkedAway) {
						goalsMarkedAway = "";
					}
				}

				var league = match.div[1].div[4].span.nodeValue;
				
				var urlImg = "http://www.fifa.com" + match.div[1].div[4].span.img.src;
				
				var json = {
					state :(state == "FT" ? "Full Time" : state),
					time :time,
					nameTeamHome :nameTeamHome,
					goalsMarkedHome :goalsMarkedHome,
					score :score,
					nameTeamAway :nameTeamAway,
					goalsMarkedAway :goalsMarkedAway,
					league :league,
					urlImg : urlImg
				}

				results.push(json);
			}

			makeTableScore(results);
		}
	} catch (err) {
		showError(err, "populateFeedScore(xmlNode, args)", 1);
	}
}

function makeTableScore(results) {
	try {
		var allTables = "";
		for ( var i = 0; i < results.length; i++) {
			var json = results[i];
			
			if (i % 2 != 0) {
				cssTable = "upDate";
			} else {
				cssTable = "downDate";
			}

			var tableScore = "<table border = 1 class='tableInformation' width = '100%'>";
			tableScore += "		<tr class='" + cssTable + "'>";
			tableScore += "			<th colspan='2'> " + json.state + " - " + json.time + " </th>";
			tableScore += "		</tr>";
			tableScore += "		<tr>";
			tableScore += "			<th width='50%'> Home </th>";
			tableScore += "			<th width='50%'> Away </th>";
			tableScore += "		</tr>";
			tableScore += "		<tr>";
			tableScore += "			<td>" + json.nameTeamHome + "</td>";
			tableScore += "			<td>" + json.nameTeamAway + "</td>";
			tableScore += "		</tr>";
			tableScore += "		<tr>";
			tableScore += "			<td colspan='2'>";
			tableScore += "				<table class='tableScore' border = 1  width = '100%'>";
			tableScore += "					<tr>";
			tableScore += "						<td  width = '45%'>" + json.goalsMarkedHome + "</td>";
			tableScore += "						<td  width = '10%'>" + json.score + "</td>";
			tableScore += "						<td  width = '45%'>" + json.goalsMarkedAway + "</td>";
			tableScore += "					</tr>";
			tableScore += "				</table>";
			tableScore += "			</td>";
			tableScore += "		</tr>";
			tableScore += "		<tr>";
			tableScore += "		</tr><td align='center' colspan='2' ><font style='font-weight: bold;'> League</font></td>";
			tableScore += "		<tr>";
			tableScore += "			<td valign='top' colspan='2' width='100%'><img width='19' height='13' src='" + json.urlImg + "'/> " + json.league + "</td>";
			tableScore += "		</tr>";
			tableScore += "	</table>";

			allTables += tableScore;
		}

		scoreDiv.innerHTML = allTables;
		displayBack(1);
	} catch (err) {
		showError(err, "makeTableScore(results)", 1);
	}
}

/**
 * Perform a search for Teams
 */
function searchTeam() {
	try {
		displayDiv(teamDiv);

		var searchFieldCountries = "<br/><table align='center' style='border-collapse: collapse;' border='0' cellspacing = '0'>";
		searchFieldCountries += "<tr>";
		searchFieldCountries += "<td class='searchYourCountry' align='center'>Search your country</td>";
		searchFieldCountries += "</tr>";
		searchFieldCountries += "<tr>";
		searchFieldCountries += "<td><input align='center' id='inputCountry' type='text' /></td>";
		searchFieldCountries += "<td><img  src='img/btnSearch.png' onclick='findCoutries();' /></td>";
		searchFieldCountries += "</tr>";
		searchFieldCountries += "</table>";
		teamDiv.innerHTML = searchFieldCountries;

		displayBack(1);
	} catch (err) {
		showError(err, "searchTeam()", 1);
	}
}

/**
 * Find the country entered
 */
function findCoutries() {
	try {
		var countryInformation = document.getElementById('inputCountry').value;
		if (!countryInformation) {
			return;
		}

		var results = new Array();

		var tmp = new RegExp(countryInformation, 'i');
		for ( var i = 0; i < countries.length; i++) {
			if (countries[i].name.search(tmp) != -1) {
				results.push(countries[i]);
			}
		}
		makeSelectCountries(countryInformation, results);
	} catch (err) {
		showError(err, "findCoutries()", 1);
	}
}

function getSelectedCountry() {
	try {
		return selectedCountry;
	} catch (err) {
		showError(err, "getSelectedCountry()", 1);
	}
}

function setSelectedCountry(name) {
	try {
		selectedCountry = name;
	} catch (err) {
		showError(err, "setSelectedCountry()", 1);
	}
}

/**
 * Create a selection of possible results for search
 * 
 * @param countryInformation -
 *            String
 * @param results -
 *            Array
 */
function makeSelectCountries(countryInformation, results) {
	try {
		var selectCountries = "<div align='center'><select id='selectCountries'  class='resultsCountries' size='4'>";
		for ( var i = 0; i < results.length; i++) {
			var country = results[i];

			if (i % 2 != 0) {
				var type = "one";
			} else {
				var type = "two";
			}

			var countryOption = "<option class='" + type + "' value='"
					+ country.url + ";" + country.urlRSS + "' label='" + country.name
					+ " (" + country.abreviation + ")'  onclick='setSelectedCountry(\""+country.name+"\");'/>";
			selectCountries = selectCountries + countryOption;
		}
		selectCountries = selectCountries + "</select></div><br/>";

		var btnMatches = "<img src='img/btnMatches.gif' onclick='requestResults();'/>";
		var btnRss = "<img src='img/btnRss.gif' onclick='loadTeamNews();'/>";
		var tableBtn = "<table align='center' border='0'><tr><td>";
		tableBtn += btnMatches + "</td><td>";
		tableBtn += btnRss + "</td></tr></table>";

		var searchFieldCountries = "	<br/>";
		searchFieldCountries += "	<table align='center' border='0' cellspacing = '1'>";
		searchFieldCountries += "		<tr>";
		searchFieldCountries += "			<td class='searchYourCountry' align='center'>Search your country</td>";
		searchFieldCountries += "		</tr>"
		searchFieldCountries += "		<tr>";
		searchFieldCountries += "			<td><input align='center' id='inputCountry' type='text' value='"
				+ countryInformation + "' /></td>";
		searchFieldCountries += "			<td><img  src='img/btnSearch.png' onclick='findCoutries();' /></td>";
		searchFieldCountries += "		</tr>";
		searchFieldCountries += "	</table><br/>";

		teamDiv.innerHTML = searchFieldCountries + selectCountries + tableBtn;
	} catch (err) {
		showError(err, "makeSelectCountries", 1);
	}
}

/**
 * Load the selected country news
 */
function loadTeamNews() {
	showLoading();

	var url = document.getElementById('selectCountries').value;
	
	if(!url){
		showInfo("Select a country!", "Your Team", 2);
		return;
	}
	
	var indexStart = url.search(";");
	url = url.substring(indexStart + 1);

	var networkUtils = new NetworkUtils();
	networkUtils.makeHttpRequest(url, networkUtils.REQUEST_METHOD_GET, null,
			"TEXT", parseNews, null);
	displayBack(2);
}

/**
 * Load the world cup news
 */
function loadCupNews() {
	showLoading();
	selectedCountry = "World Cup";

	var networkUtils = new NetworkUtils();
	networkUtils.makeHttpRequest(urlCupNews, networkUtils.REQUEST_METHOD_GET,
			null, "TEXT", parseNews, null);
	displayBack(1);
}
